/**
 * @projectName 高校就业网
 * @package com.kzj.CollegeEmploymentNetwork.interceptor
 * @className com.kzj.CollegeEmploymentNetwork.interceptor.DefaultAutoFillMybatisInterceptor
 * @copyright Copyright 2025 Thunisoft, Inc. All rights reserved.
 */
package com.kzj.CollegeEmploymentNetwork.interceptor;

import com.thunisoft.artery.util.uuid.UUIDHelper;
import com.kzj.CollegeEmploymentNetwork.common.BaseEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 *
 * DefaultMybatisInterceptors
 *
 * @description 该类可以帮助你自动填充一些公共字段，前提是你是按照“的卢”官方的SMD模板编写的，否则请自行修改
 * @author kzj
 * @date 2025年01月20日 23:11:54
 * @version 1.0.0
 */
@ConditionalOnClass(value = Interceptor.class)
@Component(value = "DefaultAutoFillMybatisInterceptor")
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
@SuppressWarnings({"unchecked", "rawtypes"})
@Order(0)
@Slf4j
public class DefaultAutoFillMybatisInterceptor implements Interceptor {

    /**
     * ATTR_COLLECTION
     */
    private static final String ATTR_COLLECTION = "collection";

    /**
     * ATTR_LIST
     */
    private static final String ATTR_LIST = "list";

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        try {
            Object[] args = invocation.getArgs();
            // TODO 自己写获取当前登录用户信息的方法
            // OrganUtil.getCurrentUser()
            // UserUtil.getCurrentUser()
            String userId = null;
            if (args.length > 1) {
                MappedStatement ms = (MappedStatement)args[0];
                if (SqlCommandType.INSERT.equals(ms.getSqlCommandType())) {
                    preInsert(args[1], userId);
                } else if (SqlCommandType.UPDATE.equals(ms.getSqlCommandType())) {
                    preUpdate(args[1], userId);
                }
            }
        } catch (Exception e) {
            log.error("intercept exception : " + e.getMessage(), e);
        }
        return invocation.proceed();
    }

    /**
     *
     * DefaultMybatisInterceptors
     *
     * @description
     * @param object 理新增时增加默认值
     * @param userId 登录用户信息
     * @author kzj
     * @date 2025年01月20日 23:11:54
     * @version 1.0.0
     */
    private void preInsert(Object object, String userId) {
        LocalDateTime now = LocalDateTime.now();
        if (object instanceof BaseEntity) {
            BaseEntity baseEntity = (BaseEntity)object;
            if (StringUtils.isBlank(baseEntity.getBh())) {
                baseEntity.setBh(UUIDHelper.getUuid());
            }
            
            baseEntity.setCjr(userId);
            baseEntity.setCjsj(now);
            baseEntity.setZhxgsj(now);
            baseEntity.setZhxgfs(1);

        } else if (object instanceof Map) {
            Map<Object, Object> map = (Map)object;
            try {
                // 处理批量操作
                List<Object> objectList = getListInMap(map);

                if (objectList != null) {
                    for (Object o : objectList) {
                        if (o instanceof BaseEntity) {
                            preInsert(o, userId);
                        }
                    }
                } else {
                    String bh = (String)map.get("bh");
                    if (StringUtils.isBlank(bh)) {
                        map.put("bh", UUIDHelper.getUuid());
                    }
                    map.put("cjsj", now);
                    map.put("zhxgsj", now);
                    map.put("zhxgfs", 1);
                }
            } catch (Exception e) {
                log.error("not found collection", e);
            }
        }
    }

    /**
     *
     * DefaultMybatisInterceptors
     *
     * @description 获取map参数中的list对象
     * @param data 参数
     * @return java.util.List<java.lang.Object>
     * @author kzj
     * @date 2025年01月20日 23:11:54
     * @version 1.0.0
     */
    private List<Object> getListInMap(Map<Object, Object> data) {
        List<Object> objectList = null;
        if (data.containsKey(ATTR_COLLECTION)) {
            objectList = (List)data.get(ATTR_COLLECTION);
        }
        if (data.containsKey(ATTR_LIST)) {
            objectList = (List)data.get(ATTR_LIST);
        }
        return objectList;
    }

    /**
     *
     * DefaultMybatisInterceptors
     *
     * @description 处理更新操作
     * @param object1 对象
     * @param userId 用户
     * @author kzj
     * @date 2025年01月20日 23:11:54
     * @version 1.0.0
     */
    private void preUpdate(Object object1, String userId) {
        LocalDateTime nowTime = LocalDateTime.now();
        if (object1 instanceof BaseEntity) {
            BaseEntity baseEntity1 = (BaseEntity)object1;
            baseEntity1.setZhxgfs(2);
            baseEntity1.setZhxgr(userId);
            baseEntity1.setZhxgsj(nowTime);
            baseEntity1.setZhxgfs(2);
        } else if (object1 instanceof Map) {
            Map<Object, Object> map1 = (Map)object1;
            try {
                List<Object> objectList1 = getListInMap(map1);
                if (objectList1 != null) {
                    for (Object o : objectList1) {
                        if (o instanceof BaseEntity) {
                            preUpdate(o, userId);
                        }
                    }
                } else {
                    map1.put("zhxgsj", nowTime);
                    map1.put("zhxgfs", 2);
                }
            } catch (Exception e) {
                log.error("not found collection", e);
            }
        }
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        log.info("setProperties ");
    }
}